package com.lcy.mapstruct;

import cn.hutool.json.JSONUtil;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.processor.util.StrUtil;
import com.lcy.codesandbox.model.JudgeInfo;
import com.lcy.model.dto.problemSubmit.OjProblemSubmitVo;
import com.lcy.model.entity.OjProblemSubmit;
import org.mapstruct.AfterMapping;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.MappingTarget;

import java.util.List;

/**
 * @author zhang.rx
 * @since 2024/5/8
 */
@Mapper(componentModel = "Spring")
public interface ProblemSubmitConverter {

	/**
	 * 将实体对象转为VO对象，确保包含createTime字段
	 */
	@Mapping(source = "createTime", target = "createTime")
	OjProblemSubmitVo toVo(OjProblemSubmit entity);

	/**
	 * 在映射完成后，设置题目名称
	 * 注意：此方法仅设置默认标题，实际标题由OjProblemSubmitServiceImpl中负责完善
	 */
	@AfterMapping
	default void setProblemTitle(@MappingTarget OjProblemSubmitVo vo, OjProblemSubmit entity) {
		if (entity != null && entity.getQuestionId() != null) {
			// 设置问题ID作为默认标题，真实标题由Service补充
			vo.setTitle("题目 #" + entity.getQuestionId());
		}
	}

	default JudgeInfo judgeInfoStrToJudgeInfoObj(String judgeInfoStr) {
		if (StrUtil.isBlank(judgeInfoStr)) {
			JudgeInfo defaultInfo = new JudgeInfo();
			defaultInfo.setMessage("代码执行成功，无详细信息");
			defaultInfo.setTime(0L);
			defaultInfo.setMemory(0L);
			return defaultInfo;
		}
		try {
			JudgeInfo judgeInfo = JSONUtil.toBean(judgeInfoStr, JudgeInfo.class);
			if (judgeInfo.getTime() == null) judgeInfo.setTime(0L);
			if (judgeInfo.getMemory() == null) judgeInfo.setMemory(0L);
			if (StrUtil.isBlank(judgeInfo.getMessage())) judgeInfo.setMessage("代码执行成功");
			return judgeInfo;
		} catch (Exception e) {
			JudgeInfo fallbackInfo = new JudgeInfo();
			fallbackInfo.setMessage("判题信息解析失败");
			fallbackInfo.setTime(0L);
			fallbackInfo.setMemory(0L);
			return fallbackInfo;
		}
	}

	List<OjProblemSubmitVo> toVoList(List<OjProblemSubmit> list);

	Page<OjProblemSubmitVo> toVoPage(Page<OjProblemSubmit> paginate);

}